<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>

        <!--        房产数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">

              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model="queryParams.address"
                  placeholder="请输入详细地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="门牌" prop="door">
                <el-input
                  v-model="queryParams.door"
                  placeholder="请输入门牌"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="宽带" prop="adslNum">
                <el-input
                  v-model="queryParams.adslNum"
                  placeholder="请输入宽带"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="月租" prop="monthPrice">
                <el-input
                  v-model="queryParams.monthPrice"
                  placeholder="请输入月租"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="截止日期" prop="endDate">
                <el-date-picker clearable
                                v-model="queryParams.endDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择截止日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="房东" prop="landlordId">
                <el-select v-model="queryParams.landlordId" placeholder="请选择房东" clearable>
                  <el-option v-for="item in landlordOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                >导出</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="info"
                  plain
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleImport"
                >导入</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="ID" align="center" prop="id" width="80" />
              <el-table-column label="地址信息" align="center">
                <template slot-scope="scope">
                  {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}{{ scope.row.street }}{{ scope.row.village }}{{ scope.row.address }}{{ scope.row.door }}
                </template>
              </el-table-column>
              <el-table-column label="宽带" align="center" prop="adslNum" />
              <el-table-column label="月租" align="center" prop="monthPrice" />
              <el-table-column label="截止日期" align="center" prop="endDate" width="100">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="房东" align="center" prop="landlordName" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-document"
                    @click="handleDocuments(scope.row)"
                  >资料管理</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>


    <!-- 添加或修改房产对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" placeholder="请选择省份" @change="provinceChangeForm">
                <el-option v-for="dict in provinceOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-select v-model="form.city" placeholder="请选择城市" @change="cityChangeForm">
                <el-option v-for="dict in cityOptionsForm" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区县" prop="district">
              <el-select v-model="form.district" placeholder="请选择区县" @change="districtChangeForm">
                <el-option v-for="dict in districtOptionsForm" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="街道" prop="street">
              <el-select v-model="form.street" placeholder="请选择街道" @change="streetChangeForm">
                <el-option v-for="dict in streetOptionsForm" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="村" prop="village">
              <el-select v-model="form.village" placeholder="请选择村">
                <el-option v-for="dict in villageOptionsForm" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="门牌" prop="door">
              <el-input v-model="form.door" placeholder="请输入门牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽带" prop="adslNum">
              <el-input v-model="form.adslNum" placeholder="请输入宽带" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="月租" prop="monthPrice">
              <el-input v-model="form.monthPrice" placeholder="请输入月租" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="endDate">
              <el-date-picker clearable
                              v-model="form.endDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择截止日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="房东" prop="landlordId">
              <el-select
                v-model="form.landlordId"
                placeholder="请输入房东姓名搜索"
                filterable
                remote
                reserve-keyword
                :remote-method="searchLandlord"
                :loading="landlordSearchLoading"
                :default-first-option="false"
                clearable
              >
                <el-option v-for="item in landlordOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 房产导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body :close-on-click-modal="false">
      <div class="import-container">
        <div class="import-tips" v-if="!upload.isUploading && !upload.isProcessing">
          <p>请先下载房产导入模板，按照模板格式填写数据后导入：</p>
          <el-button type="text" icon="el-icon-download" @click="importTemplate">下载模板</el-button>
        </div>

        <!-- 文件选择区域 -->
        <div v-if="!upload.isUploading && !upload.isProcessing">
          <el-divider content-position="center">选择文件</el-divider>
          <div class="file-info" v-if="uploadFileName">
            <i class="el-icon-document"></i>
            <span>{{ uploadFileName }}</span>
            <el-button type="text" icon="el-icon-delete" @click="clearUploadFile">清除</el-button>
          </div>
          <div class="upload-area" v-else @click="triggerFileInput">
            <input type="file" ref="fileInput" accept=".xlsx, .xls" style="display: none;" @change="handleFileChange" />
            <i class="el-icon-upload"></i>
            <div class="upload-text">点击选择Excel文件</div>
            <div class="upload-tip">仅支持.xlsx和.xls格式</div>
          </div>
        </div>

        <!-- 导入进度区域 -->
        <div v-if="upload.isUploading || upload.isProcessing" class="import-progress">
          <div class="progress-header">
            <i class="el-icon-loading"></i>
            <span>{{ upload.statusText }}</span>
          </div>

          <el-progress
            :percentage="upload.progress"
            :status="upload.progressStatus || undefined"
            :stroke-width="12"
            :show-text="true"
          ></el-progress>

          <div class="progress-details" v-if="upload.importResult">
            <div class="detail-item">
              <span class="label">总计：</span>
              <span class="value">{{ upload.importResult.total || 0 }} 条</span>
            </div>
            <div class="detail-item" v-if="upload.importResult.success">
              <span class="label">成功：</span>
              <span class="value success">{{ upload.importResult.success }} 条</span>
            </div>
            <div class="detail-item" v-if="upload.importResult.failed">
              <span class="label">失败：</span>
              <span class="value error">{{ upload.importResult.failed }} 条</span>
            </div>
          </div>

          <div class="import-log" v-if="upload.importResult && upload.importResult.message">
            <el-collapse>
              <el-collapse-item title="查看详细信息" name="1">
                <div class="log-content" v-html="upload.importResult.message"></div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!upload.isProcessing && !upload.isCompleted"
          type="primary"
          @click="submitImport"
          :loading="upload.isUploading"
          :disabled="!uploadFile || upload.isUploading"
        >
          {{ upload.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button
          v-if="upload.isCompleted"
          type="primary"
          @click="closeImportDialog"
        >
          完 成
        </el-button>
        <el-button
          @click="closeImportDialog"
          :disabled="upload.isUploading || upload.isProcessing"
        >
          {{ upload.isProcessing ? '处理中...' : '取 消' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse, importData, getImportStatus, importTemplate as downloadTemplate } from "@/api/door/house"
import request from '@/utils/request'
import { getDicts } from "@/api/system/dict/data"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {deptTreeSelect} from "@/api/system/user";

export default {
  name: "House",
  components: { Treeselect, Splitpanes, Pane },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房产表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 省份选项
      provinceOptions: [],
      // 城市选项
      cityOptions: [],
      // 区县选项
      districtOptions: [],
      // 街道选项
      streetOptions: [],
      // 村选项
      villageOptions: [],
      // 表单中的省份选项
      cityOptionsForm: [],
      // 表单中的区县选项
      districtOptionsForm: [],
      // 表单中的街道选项
      streetOptionsForm: [],
      // 表单中的村选项
      villageOptionsForm: [],
      // 房东选项
      landlordOptions: [],
      // 房东搜索加载状态
      landlordSearchLoading: false,
      // 上传的文件
      uploadFile: null,
      // 上传文件名
      uploadFileName: "",
      // 文件上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否正在处理导入
        isProcessing: false,
        // 是否完成导入
        isCompleted: false,
        // 当前状态文本
        statusText: "准备上传文件...",
        // 进度百分比
        progress: 0,
        // 进度状态
        progressStatus: null,
        // 导入结果
        importResult: null,
        // 当前导入的UUID
        importUuid: null,
        // 轮询定时器
        pollingTimer: null,
        // 进度动画定时器
        progressAnimation: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        country: "中国",
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        adslNum: null,
        monthPrice: null,
        endDate: null,
        landlordId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        province: [
          { required: true, message: "省份不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "城市不能为空", trigger: "change" }
        ],
        district: [
          { required: true, message: "区县不能为空", trigger: "change" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        landlordId: [
          { required: true, message: "房东不能为空", trigger: "change" }
        ]
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getDeptTree()

    this.getProvinceOptions()
    // 移除自动加载所有房东，改为搜索时加载
    // this.getLandlordOptions()

    // 如果是从房东管理页面跳转过来，设置房东ID
    if (this.$route.query.landlordId) {
      this.queryParams.landlordId = this.$route.query.landlordId
      // 加载对应的房东信息到选项中
      this.loadLandlordById(parseInt(this.$route.query.landlordId))
    }
  },
  beforeDestroy() {
    // 停止导入状态轮询
    this.stopPollingImportStatus()
  },
  methods: {
    /** 查询房产列表 */
    getList() {
      this.loading = true
      listHouse(this.queryParams).then(response => {
        // 处理房东名称显示
        if (response.rows && response.rows.length > 0) {
          response.rows.forEach(item => {
            const landlord = this.landlordOptions.find(l => l.id === item.landlordId)
            if (landlord) {
              item.landlordName = landlord.name
            }
          })
        }
        this.houseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 获取省份选项
    getProvinceOptions() {
      getDicts("sys_province").then(response => {
        this.provinceOptions = response.data
      })
    },
    // 省份变更
    provinceChange(val) {
      this.queryParams.city = null
      this.queryParams.district = null
      this.queryParams.street = null
      this.queryParams.village = null
      this.cityOptions = []
      this.districtOptions = []
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_city_" + val).then(response => {
          this.cityOptions = response.data
        })
      }
    },
    // 城市变更
    cityChange(val) {
      this.queryParams.district = null
      this.queryParams.street = null
      this.queryParams.village = null
      this.districtOptions = []
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_district_" + val).then(response => {
          this.districtOptions = response.data
        })
      }
    },
    // 区县变更
    districtChange(val) {
      this.queryParams.street = null
      this.queryParams.village = null
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_street_" + val).then(response => {
          this.streetOptions = response.data
        })
      }
    },
    // 街道变更
    streetChange(val) {
      this.queryParams.village = null
      this.villageOptions = []
      if (val) {
        getDicts("sys_village_" + val).then(response => {
          this.villageOptions = response.data
        })
      }
    },
    // 表单中的省份变更
    provinceChangeForm(val) {
      this.form.city = null
      this.form.district = null
      this.form.street = null
      this.form.village = null
      this.cityOptionsForm = []
      this.districtOptionsForm = []
      this.streetOptionsForm = []
      this.villageOptionsForm = []
      if (val) {
        getDicts("sys_city_" + val).then(response => {
          this.cityOptionsForm = response.data
        })
      }
    },
    // 表单中的城市变更
    cityChangeForm(val) {
      this.form.district = null
      this.form.street = null
      this.form.village = null
      this.districtOptionsForm = []
      this.streetOptionsForm = []
      this.villageOptionsForm = []
      if (val) {
        getDicts("sys_district_" + val).then(response => {
          this.districtOptionsForm = response.data
        })
      }
    },
    // 表单中的区县变更
    districtChangeForm(val) {
      this.form.street = null
      this.form.village = null
      this.streetOptionsForm = []
      this.villageOptionsForm = []
      if (val) {
        getDicts("sys_street_" + val).then(response => {
          this.streetOptionsForm = response.data
        })
      }
    },
    // 表单中的街道变更
    streetChangeForm(val) {
      this.form.village = null
      this.villageOptionsForm = []
      if (val) {
        getDicts("sys_village_" + val).then(response => {
          this.villageOptionsForm = response.data
        })
      }
    },
    // 获取房东选项
    getLandlordOptions() {
      request({
        url: '/dev-api/system/role/authUser/allocatedListNoDataScope',
        method: 'get',
        params: {
          pageNum: 1,
          pageSize: 1000,
          roleId: 100
        }
      }).then(res => {
        const rows = res.rows || []
        this.landlordOptions = rows.map(item => ({
          id: item.userId,
          name: item.nickName
        }))
        console.log(this.landlordOptions,'dkfnoi')
      })
    },
            // 搜索房东
    searchLandlord(query) {
      console.log('搜索房东被调用:', query)
      if (query && query.trim() !== '') {
        this.landlordSearchLoading = true

        request({
          url: '/dev-api/system/role/authUser/allocatedListNoDataScope',
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 50,
            roleId: 100,
            nickName: query.trim()  // 使用昵称搜索
          }
        }).then(res => {
          console.log('搜索房东结果:', res)
          const rows = res.rows || []
          this.landlordOptions = rows.map(item => ({
            id: item.userId,
            name: item.nickName
          }))
          this.landlordSearchLoading = false
        }).catch(err => {
          console.error('搜索房东失败:', err)
          this.landlordSearchLoading = false
          this.landlordOptions = []
        })
      } else {
        // 当查询为空时，显示一些提示选项或清空列表
        this.landlordOptions = []
      }
    },
    // 根据房东ID加载房东信息（编辑时使用）
    loadLandlordById(landlordId) {
      if (landlordId) {
        request({
          url: '/dev-api/system/role/authUser/allocatedListNoDataScope',
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 1000,
            roleId: 100
          }
        }).then(res => {
          const rows = res.rows || []
          const landlord = rows.find(item => item.userId === landlordId)
          if (landlord) {
            this.landlordOptions = [{
              id: landlord.userId,
              name: landlord.nickName
            }]
          }
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        country: "中国",
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        adslNum: null,
        monthPrice: null,
        endDate: null,
        landlordId: this.$route.query.landlordId || null
      }
      this.resetForm("form")
      this.cityOptionsForm = []
      this.districtOptionsForm = []
      this.streetOptionsForm = []
      this.villageOptionsForm = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 如果是从房东管理页面跳转过来，保留房东ID
      if (this.$route.query.landlordId) {
        this.queryParams.landlordId = this.$route.query.landlordId
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加房产"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getHouse(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改房产"

        // 加载级联选项
        if (this.form.province) {
          this.provinceChangeForm(this.form.province)
          if (this.form.city) {
            this.cityChangeForm(this.form.city)
            if (this.form.district) {
              this.districtChangeForm(this.form.district)
              if (this.form.street) {
                this.streetChangeForm(this.form.street)
              }
            }
          }
        }

        // 加载选中的房东信息
        if (this.form.landlordId) {
          this.loadLandlordById(this.form.landlordId)
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addHouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除房产编号为"' + ids + '"的数据项？').then(function() {
        return delHouse(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('door/house/export', {
        ...this.queryParams
      }, `house_${new Date().getTime()}.xlsx`)
    },
    /** 资料管理按钮操作 */
    handleDocuments(row) {
      this.$router.push({
        path: '/door/document/index',
        query: {
          houseId: row.id,
          houseAddress: row.province + row.city + row.district + row.street + row.village + row.address + row.door
        }
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "房产资料导入";
      this.upload.open = true;
      this.uploadFile = null;
      this.uploadFileName = "";
      this.resetUploadState();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.downloadTemplate("/door/house/importTemplate", "房产资料导入模板.xlsx");
    },
    // 触发文件选择
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择
    handleFileChange(e) {
      const files = e.target.files;
      if (files && files.length > 0) {
        this.uploadFile = files[0];
        this.uploadFileName = files[0].name;
      }
    },
    // 清除选择的文件
    clearUploadFile() {
      this.uploadFile = null;
      this.uploadFileName = "";
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = "";
      }
    },
    // 提交导入请求
    submitImport() {
      if (!this.uploadFile) {
        this.$message.warning("请先选择要上传的Excel文件");
        return;
      }

      this.upload.isUploading = true;
      this.upload.statusText = "正在上传文件...";
      this.upload.progress = 10;

      // 上传文件并获取UUID
      importData(this.uploadFile).then(response => {
        this.upload.isUploading = false;
        console.log(response,'response')
        if (response.code === 200 && response.data && response.data.uuid) {
          // 获取返回的UUID (从嵌套的data.uuid中获取)
          this.upload.importUuid = response.data.uuid;
          this.upload.isProcessing = true;
          this.upload.statusText = "正在处理导入数据...";
          this.upload.progress = 30;

          // 开始轮询导入状态
          this.startPollingImportStatus();
        } else {
          this.$message.error("上传失败: " + (response.msg || "返回数据格式错误"));
          this.resetUploadState();
        }
      }).catch(error => {
        this.upload.isUploading = false;
        this.$message.error("上传失败: " + (error.message || "网络错误"));
        this.resetUploadState();
      });
    },
    // 重置上传状态
    resetUploadState() {
      this.upload.isUploading = false;
      this.upload.isProcessing = false;
      this.upload.isCompleted = false;
      this.upload.statusText = "准备上传文件...";
      this.upload.progress = 0;
      this.upload.progressStatus = null;
      this.upload.importResult = null;
      this.upload.importUuid = null;
      this.stopPollingImportStatus();
      // 清理进度动画
      if (this.upload.progressAnimation) {
        clearInterval(this.upload.progressAnimation);
        this.upload.progressAnimation = null;
      }
    },
    // 开始轮询导入状态
    startPollingImportStatus() {
      if (!this.upload.importUuid) return;

      this.upload.pollingTimer = setInterval(() => {
        this.checkImportStatus();
      }, 2000); // 每2秒检查一次状态

      // 立即检查一次
      this.checkImportStatus();
    },
    // 停止轮询
    stopPollingImportStatus() {
      if (this.upload.pollingTimer) {
        clearInterval(this.upload.pollingTimer);
        this.upload.pollingTimer = null;
      }
    },
    // 检查导入状态
    checkImportStatus() {
      if (!this.upload.importUuid) return;

      getImportStatus(this.upload.importUuid).then(response => {
        if (response.code === 200 && response.data) {
          const status = response.data;

          // 根据状态更新进度
          this.updateImportProgress(status);

          // 如果导入完成，停止轮询
          if (status.status === 'completed' || status.status === 'failed') {
            this.stopPollingImportStatus();
            this.upload.isProcessing = false;
            this.upload.isCompleted = true;

            if (status.status === 'completed') {
              this.upload.progress = 100;
              this.upload.progressStatus = 'success';
              this.upload.statusText = "导入完成";
              this.$message.success("数据导入成功");
              this.getList(); // 刷新列表
            } else {
              this.upload.progressStatus = 'exception';
              this.upload.statusText = "导入失败";
              this.$message.error("数据导入失败");
            }

            // 保存导入结果
            this.upload.importResult = status;
          }
        }
      }).catch(error => {
        console.error("查询导入状态失败:", error);
        // 发生错误时不立即停止轮询，可能是网络临时问题
      });
    },
        // 更新导入进度
    updateImportProgress(status) {
      let targetProgress = this.upload.progress;

      switch (status.status) {
        case 'uploading':
          targetProgress = 20;
          this.upload.statusText = "文件上传中...";
          break;
        case 'parsing':
          targetProgress = 40;
          this.upload.statusText = "正在解析Excel文件...";
          break;
        case 'validating':
          targetProgress = 60;
          this.upload.statusText = "正在验证数据...";
          break;
        case 'importing':
          targetProgress = 80;
          this.upload.statusText = "正在导入数据...";
          break;
        case 'completed':
          targetProgress = 100;
          this.upload.progressStatus = 'success';
          this.upload.statusText = "导入完成";
          break;
        case 'failed':
          this.upload.progressStatus = 'exception';
          this.upload.statusText = status.message || "导入失败";
          break;
        default:
          this.upload.statusText = "正在处理...";
      }

      // 如果有具体进度信息，使用具体进度
      if (status.progress && status.progress > targetProgress) {
        targetProgress = Math.min(status.progress, 99);
      }

      // 平滑更新进度条
      this.animateProgress(targetProgress);
    },
    // 平滑动画更新进度
    animateProgress(targetProgress) {
      if (this.upload.progressAnimation) {
        clearInterval(this.upload.progressAnimation);
      }

      const currentProgress = this.upload.progress;
      const difference = targetProgress - currentProgress;

      if (difference <= 0) return;

      const steps = 20; // 动画步数
      const stepSize = difference / steps;
      const stepDelay = 100; // 每步延迟100ms

      let currentStep = 0;

      this.upload.progressAnimation = setInterval(() => {
        currentStep++;

        if (currentStep >= steps) {
          this.upload.progress = targetProgress;
          clearInterval(this.upload.progressAnimation);
          this.upload.progressAnimation = null;
        } else {
          this.upload.progress = Math.round(currentProgress + (stepSize * currentStep));
        }
      }, stepDelay);
    },
    // 关闭导入对话框
    closeImportDialog() {
      this.stopPollingImportStatus();
      this.upload.open = false;
      this.resetUploadState();
      this.clearUploadFile();
    }
  }
}
</script>

<style scoped>
/* 导入对话框样式 */
.import-container {
  padding: 10px 0;
}

.import-tips {
  margin-bottom: 15px;
}

.upload-area {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  padding: 30px 0;
  margin: 10px 0;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-area .el-icon-upload {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

.file-info {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin: 10px 0;
  background-color: #f9f9f9;
}

.file-info i {
  color: #909399;
  margin-right: 8px;
  font-size: 18px;
}

/* 导入进度样式 */
.import-progress {
  padding: 20px 0;
}

.progress-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.progress-header i {
  margin-right: 8px;
  color: #409EFF;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.progress-details {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  color: #606266;
  font-weight: 500;
}

.detail-item .value {
  font-weight: bold;
}

.detail-item .value.success {
  color: #67c23a;
}

.detail-item .value.error {
  color: #f56c6c;
}

.import-log {
  margin-top: 15px;
}

.log-content {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.5;
  color: #606266;
}

/* 进度条样式调整 */
.el-progress {
  margin: 10px 0;
}

.el-progress__text {
  font-weight: bold;
}
</style>
